//
//  VideoAudioPOPView.swift
//  NDAi
//
//  Created by 丸子 on 2024/6/21.
//

import UIKit
import AVFoundation

class VideoAudioPOPView: UIView, AVAudioPlayerDelegate {
    let viewHeight:CGFloat = 418 + kSafeHeight
    var dataSource:[VideoVoiceModel] = []
    var chooseVoice:( (VideoVoiceModel) -> Void)?
    private lazy var backView: UIView = {
        let view = UIView(frame: CGRect(x: 0, y: SCREEN_HEIGHT, width: SCREEN_WIDTH, height: viewHeight))
        view.backgroundColor = UIColor(hexString: "#221D30")
        return view
    }()
    private lazy var titleLb: UILabel = {
        let label = UILabel()
        label.textColor = UIColor.white
        label.font = UIFont.pingFangSCRegular(ofSize: 15)
        label.text = "人物配音"
        return label
    }()
    
    private lazy var closeBtn: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage(UIImage(named: "icon_video_close"), for: .normal)
        return button
    }()
    private lazy var tableView: UITableView = {
        let view = UITableView(frame: .zero, style: .plain)
        view.backgroundColor = .clear
        view.delegate = self
        view.dataSource = self
        view.register(cellWithClass: VideoAudioStyleCell.self)
        view.rowHeight = UITableView.automaticDimension
        view.sectionHeaderHeight = 0
        view.estimatedSectionHeaderHeight = 0
        view.sectionFooterHeight = 0
        view.estimatedSectionFooterHeight = 0
        view.contentInsetAdjustmentBehavior = .never
        view.separatorStyle = .none
        return view
    }()
    
    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: SCREEN_HEIGHT))
        backgroundColor  = UIColor(hexString: "#000000", transparency: 0.3)
        backView.corners([.layerMinXMinYCorner, .layerMaxXMinYCorner], cornerRadius: 8)
        addSubview(backView)
        backView.addSubviews([titleLb, closeBtn, tableView])
        titleLb.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(12)
            make.leading.equalToSuperview().offset(16)
            make.height.equalTo(45)
        }
        
        closeBtn.snp.makeConstraints { make in
            make.centerY.equalTo(titleLb)
            make.trailing.equalToSuperview().offset(-16)
            make.height.equalTo(36)
        }
        
        tableView.snp.makeConstraints { make in
            make.top.equalTo(closeBtn.snp.bottom).offset(12)
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(-kSafeHeight)
        }
        
        
        closeBtn.setClosureTouchUpInside_k { [weak self] in
            self?.hide()
        }
    }
    func show(){
        Appearance.addViewToWindow(self)
        UIView.animate(withDuration: 0.3, animations: {
            self.backView.frame = CGRect(x: 0, y: SCREEN_HEIGHT - self.viewHeight, width: SCREEN_WIDTH, height: self.viewHeight)
        })
    }
    
    func hide(){
        UIView.animate(withDuration: 0.3, animations: {
            self.backView.frame = CGRect(x: 0, y: SCREEN_HEIGHT, width: SCREEN_WIDTH, height: self.viewHeight)
        }, completion: { _ in
            self.removeFromSuperview()
        })
    }
    
    func setup(models:[VideoVoiceModel]){
        self.dataSource = models
        self.tableView.reloadData()
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var audioPlayer: AVAudioPlayer?
    
}
extension VideoAudioPOPView: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        self.dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let model = self.dataSource[indexPath.item]
        let cell = tableView.dequeueReusableCell(withClass: VideoAudioStyleCell.self)
        cell.backView.layer.borderColor = UIColor(hexString: "#34fefe").cgColor
        cell.sgLb.text = "\(model.title ?? "")-\(model.theme ?? "")"
        cell.iconIV.image = UIImage(named: "icon_login_a")
        if model.isSelect == true {
            cell.backView.layer.borderWidth = 1
            cell.selectIV.isHidden = false
        }else {
            cell.backView.layer.borderWidth = 0
            cell.selectIV.isHidden = true
        }
        if model.isPlayer == true {
            cell.playlb.isHidden = false
        }else {
            cell.playlb.isHidden = true
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 66
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = self.dataSource[indexPath.item]
        for (index,value) in self.dataSource.enumerated() {
            self.dataSource[index].isSelect = false
        }
        for (index,value) in self.dataSource.enumerated() {
            self.dataSource[index].isPlayer = false
        }
        self.dataSource[indexPath.item].isSelect = true
        self.dataSource[indexPath.item].isPlayer = true
        self.tableView.reloadData()
        self.startPlayerVoice(model: model)
        
        self.chooseVoice?(model)
    }
    
    func startPlayerVoice(model:VideoVoiceModel){
        guard let url = URL(string: model.audio_url ?? "") else {
            print("Invalid URL")
            return
        }
        // Download the audio file data
        URLSession.shared.dataTask(with: url) { [weak self] data, response, error in
            guard let self = self else { return }
            if let error = error {
                print("Error downloading audio file: \(error)")
                return
            }
            guard let data = data else {
                print("No data received")
                return
            }
            do {
                // Initialize the audio player
                self.audioPlayer = try AVAudioPlayer(data: data)
                self.audioPlayer?.delegate = self
                self.audioPlayer?.prepareToPlay()
                self.audioPlayer?.play()
            } catch {
                print("Error initializing audio player: \(error)")
            }
        }.resume()
    }
    
    
    // AVAudioPlayerDelegate method
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        if flag {
            for (index,value) in self.dataSource.enumerated() {
                self.dataSource[index].isPlayer = false
            }
            self.tableView.reloadData()
            print("Audio finished playing successfully")
            // Perform your callback actions here
        } else {
            for (index,value) in self.dataSource.enumerated() {
                self.dataSource[index].isPlayer = false
            }
            self.tableView.reloadData()
            print("Audio did not finish playing successfully")
        }
    }
    
}

